package com.serviceprovider.business.module.sp.preferences.dao.impl;

//~--- non-JDK imports --------------------------------------------------------

import com.serviceprovider.business.module.sp.preferences.dao.interfaces.IPreferencesDao;
import com.serviceprovider.business.module.sp.preferences.model.Preferences;
import com.serviceprovider.business.module.user.model.impl.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

//~--- JDK imports ------------------------------------------------------------

import java.util.HashMap;
import java.util.Map;

/**
 * DAO for preferences. Implementation of IPreferencesDao
 *
 * @author mrduongnv@gmail.com
 */
@Repository("preferencesDao")
public class PreferencesDao extends SimpleJdbcDaoSupport implements IPreferencesDao {
    @Qualifier("preferencesJdbcInsert")
    @Autowired
    private SimpleJdbcInsert jdbcInsert;

    @Autowired
    public PreferencesDao(@Qualifier("jdbcTemplate") JdbcTemplate jdbcTemplate) {
        setJdbcTemplate(jdbcTemplate);
    }

    public Preferences findByUserId(int userId) {
        String sql =
            new StringBuffer().append("select * from sp_preferences where user_id = ").append(userId).toString();

        try {
            return getSimpleJdbcTemplate().queryForObject(sql, new PreferencesMapper());
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    public Preferences createPreferences(Preferences preferences) {
        if (preferences == null) {
            throw new IllegalArgumentException("Preferences object can't be null");
        }

        if (preferences.getUser() == null) {
            throw new IllegalArgumentException("User attribute can't be null");
        }

        Map<String, Object> parameters = new HashMap<String, Object>();

        parameters.put("user_id", preferences.getUser().getId());
        parameters.put("bonus", preferences.getBonus());
        parameters.put("custom_fee", preferences.getCustomFee());
        parameters.put("commission", preferences.getComission());

        Number id = jdbcInsert.executeAndReturnKey(parameters);

        preferences.setId(id.intValue());

        return preferences;
    }

    public void updatePreferences(Preferences preferences) {
        if (preferences == null) {
            throw new IllegalArgumentException("Preferences object can't be null");
        }

        if (preferences.getUser() == null) {
            throw new IllegalArgumentException("User attribute can't be null");
        }

        String query = new StringBuffer().append(" UPDATE sp_preferences SET ").append(" user_id = ?, ").append(
                           " bonus = ?, ").append(" custom_fee = ?, ").append(" commission = ? ").append(
                           " WHERE id = ? ").toString();

        getSimpleJdbcTemplate().update(query, preferences.getUser().getId(), preferences.getBonus(),
                                       preferences.getCustomFee(), preferences.getComission());
    }

    public Preferences saveDefaultFee(User user, Integer fee) {
        if ((user == null) || (user.getId() == null)) {
            throw new IllegalArgumentException("User object can't be null");
        }

        // If preferences for given user already exists then we update them with fee value
        Preferences preferences = this.findByUserId(user.getId());

        if (preferences != null) {
            preferences.setCustomFee(fee);
            this.updatePreferences(preferences);

            return preferences;
        }

        // Preferences for given user doesn't exists so we create a new record and save default fee value in it
        preferences = new Preferences();
        preferences.setUser(user);
        preferences.setCustomFee(fee);

        return this.createPreferences(preferences);
    }
}



